function getOption(graphInfo){
//给节点设置样式
    let nodes=graphInfo['nodes'];
    let links=graphInfo['links'];
    //console.log(links);
//设置option样式
    return {
        title: {
            text: title,
            left: 'center',
            textStyle:{
                fontSize:15
            },
            bottom:0
        },
        tooltip: {
            trigger: 'item'
        },
        backgroundColor:'white',
        roam: true,
        series: [
            {
                type: 'graph',
                layout: 'none',
                symbol: "circle",
                edgeSymbol:['none', 'arrow'],
                symbolSize: 27,
                edgeSymbolSize: 10,
                nodes: nodes,
                links: links,
                label: {
                    normal: {
                        show: true
                    }
                },
                draggable:true
            }
        ]
    };
}
function nodeStyle(title,x,y,weight){
   return  { 
       name: title,
       x:x,
       y:y,
       value:weight,
       symbolSize:symbolSize,
       itemStyle: {
           borderColor: 'black',
           color:'white',
           borderWidth: 3
        },
       label:{
           show:true,
           formatter:'{b}-{c}',
           position:"inside",
           fontSize:labelFontSize,
           color:'black',
           fontWeight:'bold'
        }
    }
}
function nodeStyle1(title,x,y,weight){
   return  { 
       name: title,
       x:x,
       y:y,
       value:weight,
       symbolSize:symbolSize,
       itemStyle: {
           borderColor: 'white',
           color:'black',
           borderWidth: 3
        },
       label:{
           show:true,
           formatter:'{c}',
           position:"inside",
           fontSize:labelFontSize,
           color:'white',
           fontWeight:'bold'
        }
    }
}
function edgeStyle(selectNode,value){
    return {
        source: selectNode[0],
        target: selectNode[1],
        value:value,
        lineStyle: {
            width: 5,
            color: '#000',
            type:'solid',
            opacity:0.8,
            ignoreForceLayout:true
        },
        label:{
             show:true,
             formatter:'{c}',
             fontSize:15,
             fontWeight:'bold'
        }
    };
}
//获取节点
function getNodes(weightArr,titleArr){
    let nodes=[];
    NodeList=[];
    let Num=weightArr.length;
    let str="";
    let nodeTitle=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
    if(titleArr.length==0){
        for(let i=0;i< Num;i++){
            str="";
            for(let j=0;j<=parseInt(i/26);j++){
                str+=nodeTitle[i-parseInt(i/26)*26];
            }
            titleArr.push(str);
        }
    }
    for(let i=0;i< Num;i++){
        nodes.push(nodeStyle(titleArr[i],Math.floor(i*100/Num),70,weightArr[i]));
        NodeList.push({
            left:null,
            right:null,
            weight:weightArr[i], //权重
            index:i,  //nodes下标
            title:titleArr[i] //标签
        })
    }
    return nodes;
}
function showResults(currentRoot,item){
    if(currentRoot.left==null){
        results.push({
            obj:currentRoot.title,
            num:currentRoot.weight,
            code:item
        })
    }
    else{
        console.log(currentRoot.left);
        console.log(currentRoot.right);
        showResults(currentRoot.left,item+'0');
        showResults(currentRoot.right,item+'1');
    }
}
function getNextMinNode(){
    if(NodeList.length==1){
        modalApp.modalAlert('最优二叉树生成完毕');
        showResults(NodeList[0],'');
        app.setResult(results);
        console.log(results);
        return;
    }
    NodeList.sort((x,y)=>{
        return x.weight-y.weight;
    });
    console.log(NodeList);
    min1Node=NodeList[0];
    min2Node=NodeList[1];
    //console.log(min1Node);
    //console.log(min2Node);
    let t1=currentRoot.indexOf(min1Node);
    let t2=currentRoot.indexOf(min2Node);
    if(t1==-1&&t2==-1){
        //两个是新节点  放在最大根节点的右子节点向右移20开始
        currentRoot.unshift(min2Node);
        currentRoot.unshift(min1Node);
        console.log(currentRoot);
        let dx=getLeftX(currentRoot[2])
        nodes[min2Node.index].x=dx-20;
        nodes[min2Node.index].y=nodes[currentRoot[2].index].y;
        nodes[min1Node.index].x=dx-40;
        nodes[min1Node.index].y=nodes[currentRoot[2].index].y;
    }
    else if(t1==-1&&t2!=-1){
        currentRoot.unshift(min1Node);
        console.log(currentRoot);
        let dx=getLeftX(currentRoot[1]);
        nodes[min1Node.index].x=dx-20;
        nodes[min1Node.index].y=nodes[currentRoot[1].index].y;
    }
    else if(t1!=-1&&t2==-1){
        currentRoot.splice(1,0,min2Node);
        let dx=getRightX(currentRoot[0]);
        nodes[min2Node.index].x=dx+20;
        nodes[min2Node.index].y=nodes[currentRoot[0].index].y;
        for(let i=2;i<currentRoot.length;i++){
            dealNodeLocationX(currentRoot[i],20);
        }
    }
    else{
        //不动
    }
    myChart.setOption(option);

}
function getLeftX(Node){
    if(Node.left!=null){
        return getLeftX(Node.left);
    }
    else{
        return nodes[Node.index].x;
    }
}
function getRightX(Node){
    if(Node.right!=null){
        return getRightX(Node.right);
    }
    else{
        return nodes[Node.index].x;
    }
}

function dealNodeLocationX(rootNode,dx){
    if(rootNode.left==null){
        nodes[rootNode.index].x+=dx;
    }
    else{
        nodes[rootNode.index].x+=dx;
        dealNodeLocationX(rootNode.left,dx);
        dealNodeLocationX(rootNode.right,dx);
    }
}
function dealNodeLocationY(rootNode,dy){
    //console.log(dy);
    if(rootNode.left==null){
        nodes[rootNode.index].y+=dy;
        //console.log(nodes[rootNode.index].y);
    }
    else{
        nodes[rootNode.index].y+=dy;
        //console.log(nodes[rootNode.index].y);
        dealNodeLocationY(rootNode.left,dy);
        dealNodeLocationY(rootNode.right,dy);
    }
}
function dealMinNodes(){
    //两个顶点相加 得到的值加入比较队列
    //console.log(NodeList);
    //找到两个权值最小的点
    if(NodeList.length==1){
        modalApp.modalAlert('最优二叉树生成完毕');
        return;
    }
    //构造新的节点
    let newNode={
        left:min1Node,    //左子节点
        right:min2Node,   //右子节点
        weight:min1Node.weight+min2Node.weight, //权重
        index:nodes.length,  //nodes下标
        title:min1Node.index+"-"+min2Node.index //标签
    }
    //图 添加新的节点 设置坐标为两个最小点的x1+x2/2 y1+20
    let newX=(nodes[min1Node.index].x+nodes[min2Node.index].x)/2;
    let newY=nodes[min1Node.index].y-20;
    nodes.push(nodeStyle1(newNode.title,newX,newY,newNode.weight));
    //添加新的连接
    links.push(edgeStyle([newNode.index,min1Node.index],0));
    links.push(edgeStyle([newNode.index,min2Node.index],1));
    treeNodeList.push(nodes[newNode.index]);
    currentRoot.push(newNode);  //设置根节点
    console.log(currentRoot);
    let t1=currentRoot.indexOf(min1Node);
    if(t1!=-1) currentRoot.splice(t1,1);
    let t2=currentRoot.indexOf(min2Node);
    if(t2!=-1) currentRoot.splice(t2,1);
    console.log(min1Node);
    console.log(min2Node);
    console.log(currentRoot);
    NodeList.shift(); //压出第一个最小权值的元素
    NodeList.shift();//压出第二个最小权值的元素
    NodeList.push(newNode);//压入新的权值的元素
    nodes[newNode.index].itemStyle.color='black';
    nodes[newNode.index].label.color='white';
    //对所有的根节点进行重新排序
    currentRoot.sort((x,y)=>{
        return x.weight-y.weight;
    });
    let y=nodes[currentRoot[0].index].y;
    let rightX=getRightX(currentRoot[0]);
    for(let i=1;i<currentRoot.length;i++){
        let dy=y-nodes[currentRoot[i].index].y;
        dealNodeLocationY(currentRoot[i],dy);
        //处理x位置
        let dx=20+rightX-getLeftX(currentRoot[i]);
        dealNodeLocationX(currentRoot[i],dx);
        rightX=getRightX(currentRoot[i]);
    }
    myChart.setOption(option);
}
//初始化数据
function initData(){
    weightArr=[]; //权值列表
    titleArr=[];
    nodes=[];
    links=[];option={};
    title="";
    treeNodeList=[];
    NodeList=[];
    nextMinNode=false;
    min1Node={};min2Node={};
    results=[];
    currentRoot=[];
}
//由字母获取 下标  eulerianPathSet转 每一条边 逐步显示
function getIndex(letter){
  let nodeTitle=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
  let len=letter.length;
  let l=letter[0];
  let index=getArrayIndex(nodeTitle,l);
  return index+26*(len-1);
}
function getArrayIndex(arr, obj) {
    var i = arr.length;
    while (i--) {
        if (arr[i] === obj) {
            return i;
        }
    }
    return -1;
}
//显示红色
function showLinksRed(index1,index2){
    let index=0;
    for(let i=0;i<links.length;i++){
        if((links[i].source==index1&&links[i].target==index2)||(links[i].source==index2&&links[i].target==index1))
        {
            index=i;
            break;
        }
    }
    option.series[0].links[index].lineStyle.color="red";
    option.series[0].links[index].lineStyle.width=10;
    myChart.setOption(option);
}
//逐步显示过程
function nextEdges(){
    treeNodeList.sort((x,y)=>{
        return x.weight-y.weight;
    });    
}
function getTitleWeight(arr){
    let weightArr=[]; //权值列表
    let titleArr=[];
    let numList=[];
    for(let i=0;i<arr.length;i++){
        if(numList[arr[i]]==null){
            numList[arr[i]]=1;
        }
        else numList[arr[i]]++;
    }
    for(let o in numList){
        weightArr.push(numList[o]);
        titleArr.push(o);
    }
    console.log(weightArr);
    console.log(titleArr);
    return {weightArr,titleArr};
}

let myChart = echarts.init(document.getElementById('echartsDiv'));
let weightArr=[]; //权值列表
let titleArr=[];
let treeNodeList=[];// 二叉树的数据模型
let NodeList=[];// 用于比较大小的节点队列
let currentRoot=[]; //当前根节点列表
let min1Node,min2Node;
let currentTree; //当前 样例数据
let nodes=[],links=[],option={},title="";  //显示图的点集和边集
let showEdgeIndex=0;  //逐步显示边的下标
let nextMinNode=false; //是否进行找第二个最小的值 false 为生成新的根节点
let results=[];  //二叉树的计算结果
let symbolSize=40;
let labelFontSize=15;
var app=new Vue({
    el: '#app',
    data: {
       showResult:false,
       results:[],
       treeList:[
        {
            type:'array',
            content:[9,12,6,3,5,15]
        },
        {
            type:'string',
            content:['A','F','T','E','R','D','A','T','A','E','A','R','A','R','E','A','R','T','A','R','E','A']
        },
        {
            type:'objArr',
            content:[
                {
                    title:'空',weight:4
                },
                {
                    title:'t',weight:3
                },
                {
                    title:'b',weight:2
                },
                {
                    title:'e',weight:2
                },
                {
                    title:'s',weight:2
                },
                {
                    title:'a',weight:1
                },
                {
                    title:'h',weight:1
                },
                {
                    title:'i',weight:1
                }
            ]
        },
        {
            type:'array',
            content:[3,3,4,2,2]
        },
        {
            type:'objArr',
            content:[
                {
                    title:'A',weight:5
                },
                {
                    title:'B',weight:29
                },
                {
                    title:'C',weight:7
                },
                {
                    title:'*',weight:8
                },
                {
                    title:'%',weight:14
                },
                {
                    title:'@',weight:23
                },
                {
                    title:'#',weight:3
                },
                {
                    title:'K',weight:11
                }
            ]
        },
        {
            type:'string',
            content:['B','T','T','E','R','R','A','T','A','E','A','R','A','R','E','A','R','T','A','R','E','A']
        },
      ],
      title:'',
      num:'',
      examples:['样例1','样例2','样例3']
    },
    methods:{
        showGraph(index){
            initData();
            this.showResult=false;
            this.results=[];
            console.log(index);
            currentTree=this.treeList[index];
            if(currentTree.type=="array"){
                weightArr=currentTree.content;
            }
            else if(currentTree.type=="objArr"){
                for(let i=0;i<currentTree.content.length;i++){
                    weightArr.push(currentTree.content[i].weight);
                    titleArr.push(currentTree.content[i].title);
                }
            }
            else{
                let obj=getTitleWeight(currentTree.content);
                weightArr=obj.weightArr;
                titleArr=obj.titleArr;
            }
            nodes=getNodes(weightArr,titleArr);
            for(let i=0;i<weightArr.length;i++){
                title+="[ "+titleArr[i]+'-'+weightArr[i]+" ]"
            }
            let jsonData={"nodes":nodes,"links":links}
            option=getOption(jsonData);
            myChart.setOption(option);
        },
        algorithmRun(){
            if(nodes.length==0){
                modalApp.modalAlert('未选择序列');
                return;
            }
            if(treeNodeList.length>0){
                this.resetProcess();
            }
            //显示过程
            modalApp.modalAlert('运算完毕,点击显示过程');
            NodeList.sort((x,y)=>{
                 return x.weight-y.weight;
            });
            //console.log(NodeList);
            min1Node=NodeList[0];
            min2Node=NodeList[1];
            nodes[min1Node.index].x=40;
            nodes[min1Node.index].y=50;
            nodes[min2Node.index].x=60;
            nodes[min2Node.index].y=50;
            treeNodeList.push(NodeList[0]);
            treeNodeList.push(NodeList[1]);
            myChart.setOption(option);
        },
        showNext(){
            if(treeNodeList.length>0){
                if(nextMinNode){
                    getNextMinNode();
                    nextMinNode=false;
                }
                else{
                    dealMinNodes();
                    nextMinNode=true;
                } 
            }  
            else{
                modalApp.modalAlert('未加载数据');
            }
        },
        resetProcess(){
            //重置显示
            nextMinNode=false;
            title="";
            title="";
            treeNodeList=[];
            NodeList=[];
            min1Node={};min2Node={};
            results=[];
            currentRoot=[];
            if(currentTree.type=="array"){
                weightArr=currentTree.content;
            }
            else{
                let obj=getTitleWeight(currentTree.content);
                weightArr=obj.weightArr;
                titleArr=obj.titleArr;
            }
            
            nodes=getNodes(weightArr,titleArr);
            for(let i=0;i<weightArr.length;i++){
                title+="[ "+titleArr[i]+'-'+weightArr[i]+" ]"
            }
            let jsonData={"nodes":nodes,"links":links}
            option=getOption(jsonData);
            myChart.setOption(option);
        },
        setResult(result){
            console.log(result);
            let sum=0;
            for(let i=0;i<result.length;i++){
                sum+=result[i].num;
            }
            for(let i=0;i<result.length;i++){
                result[i].num=parseInt(result[i].num*100/sum)+'%';
                this.results.push(result[i]);
            }
            this.showResult=true;
        },
        addData(){
            console.log("aa")
            if(this.title==""||this.num==""){
                modalApp.modalAlert('未输入');
            }
            else{
               for(let i=0;i<NodeList.length;i++){
                   if(this.title==NodeList[i].title){
                       modalApp.modalAlert('字符重复');
                       return;
                   }
               }
               nodes.push(nodeStyle(this.title,10*(nodes.length+1),70,parseInt(this.num)))
               console.log(nodes)
               if(nodes.length==1){
                   let jsonData={"nodes":nodes,"links":links}
                   option=getOption(jsonData);
               }
               NodeList.push({
                    left:null,
                    right:null,
                    weight:parseInt(this.num), //权重
                    index:nodes.length-1,  //nodes下标
                    title:this.title //标签
               })
               title+="["+this.title+"-"+this.num+"]";
               myChart.setOption(option);
            }
        },
        resetData(){
            initData();
            this.showResult=false;
            this.results=[];
            this.title='',this.num='';
            myChart.clear();
        }
    }
})
var modalApp=new Vue({
    el:"#myModal1",
    data:{
        message:""
    },
    methods:{
        modalAlert(str){
            this.message=str;
            $('#myModal1').modal('toggle');
        }
    }
})
var windowWidth = $(window).width();
    if(windowWidth < 767.98){
        // do something
        //手机屏幕 点的大小变小
        symbolSize=20;
        labelFontSize=9;
    }
    if(windowWidth >= 767.98){
        // do something
         console.log("0")
}